/**
 * 视频进度跟踪器
 * 负责统计用户观看视频的进度、时长和播放位置，并定期上报到后端
 */

import { StudyService } from '@/api/services';
import { progressCache, CACHE_TYPES, CACHE_EXPIRY } from './progressCache';

export interface ProgressData {
  progress: number;        // 观看进度百分比 (0-100)
  watch_time: number;      // 本次观看时长(秒)
  current_position: number; // 当前播放位置(秒)
}

export interface LessonProgressResponse {
  lessonProgress: {
    id: number;
    lessonId: number;
    progress: number;
    watchTime: number;
    currentPosition: number;
    isCompleted: boolean;
    lastWatchAt: string;
  };
  courseProgress: {
    progress: number;
    currentLesson: number;
    totalLessons: number;
    completedLessons: number;
    totalStudyTime: number;
  };
}

export class VideoProgressTracker {
  private courseId: number;
  private lessonId: number;
  private duration: number = 0;

  // 进度统计相关
  private startTime: number = 0;
  private lastReportTime: number = 0;
  private lastPosition: number = 0;
  private totalWatchTime: number = 0;
  private currentProgress: number = 0;

  // 配置参数
  private reportInterval: number = 30000; // 30秒上报一次
  private minWatchTime: number = 5; // 最小观看时长5秒才上报
  private progressThreshold: number = 5; // 进度变化5%才上报

  // 状态管理
  private isPlaying: boolean = false;
  private isTracking: boolean = false;
  private reportTimer: number | null = null;

  // 缓存相关
  private resumePositionCache: number | null = null;
  private resumePositionFetched: boolean = false;
  
  constructor(courseId: number, lessonId: number) {
    this.courseId = courseId;
    this.lessonId = lessonId;
    console.log(`📊 初始化视频进度跟踪器 - 课程ID: ${courseId}, 课时ID: ${lessonId}`);
  }

  /**
   * 设置视频时长
   */
  setDuration(duration: number): void {
    this.duration = duration;
    console.log(`⏱️ 设置视频时长: ${duration}秒`);
  }

  /**
   * 开始跟踪
   */
  startTracking(): void {
    if (this.isTracking) return;
    
    this.isTracking = true;
    this.startTime = Date.now();
    this.lastReportTime = Date.now();
    
    // 启动定期上报
    this.startReportTimer();
    
    console.log('🎬 开始跟踪视频进度');
  }

  /**
   * 停止跟踪
   */
  stopTracking(): void {
    if (!this.isTracking) return;
    
    this.isTracking = false;
    this.isPlaying = false;
    
    // 停止定期上报
    this.stopReportTimer();
    
    // 最后一次上报
    this.reportProgress(true);
    
    console.log('⏹️ 停止跟踪视频进度');
  }

  /**
   * 播放事件
   */
  onPlay(): void {
    this.isPlaying = true;
    this.startTime = Date.now();
    console.log('▶️ 视频开始播放');
  }

  /**
   * 暂停事件
   */
  onPause(): void {
    if (this.isPlaying) {
      const watchTime = (Date.now() - this.startTime) / 1000;
      this.totalWatchTime += watchTime;
      console.log(`⏸️ 视频暂停，本次观看时长: ${watchTime.toFixed(1)}秒`);
    }
    this.isPlaying = false;
  }

  /**
   * 时间更新事件
   */
  onTimeUpdate(currentTime: number): void {
    if (!this.isTracking || !this.duration) return;
    
    this.lastPosition = currentTime;
    const newProgress = (currentTime / this.duration) * 100;
    
    // 检查进度是否有显著变化
    if (Math.abs(newProgress - this.currentProgress) >= this.progressThreshold) {
      this.currentProgress = newProgress;
      console.log(`📈 进度更新: ${newProgress.toFixed(1)}%`);
    }
  }

  /**
   * 视频结束事件
   */
  onEnded(): void {
    console.log('🏁 视频播放结束');
    this.currentProgress = 100;
    this.onPause();
    this.reportProgress(true); // 立即上报完成状态
  }

  /**
   * 启动定期上报定时器
   */
  private startReportTimer(): void {
    this.stopReportTimer();
    this.reportTimer = window.setInterval(() => {
      if (this.isTracking) {
        this.reportProgress();
      }
    }, this.reportInterval);
  }

  /**
   * 停止定期上报定时器
   */
  private stopReportTimer(): void {
    if (this.reportTimer) {
      clearInterval(this.reportTimer);
      this.reportTimer = null;
    }
  }

  /**
   * 上报进度到后端
   */
  private async reportProgress(force: boolean = false): Promise<void> {
    const now = Date.now();
    
    // 计算本次观看时长
    let currentWatchTime = 0;
    if (this.isPlaying) {
      currentWatchTime = (now - this.startTime) / 1000;
      this.totalWatchTime += currentWatchTime;
      this.startTime = now; // 重置开始时间
    }
    
    // 检查是否需要上报
    const timeSinceLastReport = now - this.lastReportTime;
    const shouldReport = force || 
                        (timeSinceLastReport >= this.reportInterval && this.totalWatchTime >= this.minWatchTime);
    
    if (!shouldReport) return;
    
    const progressData: ProgressData = {
      progress: Math.round(this.currentProgress * 100) / 100, // 保留2位小数
      watch_time: Math.round(this.totalWatchTime),
      current_position: Math.round(this.lastPosition)
    };
    
    console.log('📤 上报进度数据:', progressData);
    
    try {
      const result = await StudyService.updateLessonProgress(
        this.courseId,
        this.lessonId,
        progressData
      );
      
      if (result && result.code === 200) {
        console.log('✅ 进度上报成功:', result.data);

        // 更新缓存中的断点续播位置
        if (result.data && result.data.lessonProgress) {
          const newPosition = result.data.lessonProgress.currentPosition || this.lastPosition;
          progressCache.set(
            this.courseId,
            this.lessonId,
            CACHE_TYPES.RESUME_POSITION,
            newPosition,
            CACHE_EXPIRY.SHORT
          );
          this.resumePositionCache = newPosition;
        }

        // 重置统计数据
        this.totalWatchTime = 0;
        this.lastReportTime = now;

        // 返回进度数据供外部使用
        return result.data as LessonProgressResponse;
      } else {
        console.warn('⚠️ 进度上报失败:', result);
      }
    } catch (error) {
      console.error('❌ 进度上报异常:', error);
    }
  }

  /**
   * 获取当前进度信息
   */
  getCurrentProgress(): {
    progress: number;
    watchTime: number;
    currentPosition: number;
  } {
    return {
      progress: this.currentProgress,
      watchTime: this.totalWatchTime,
      currentPosition: this.lastPosition
    };
  }

  /**
   * 获取断点续播位置
   */
  async getResumePosition(): Promise<number> {
    // 首先检查全局缓存
    const cachedPosition = progressCache.get(this.courseId, this.lessonId, CACHE_TYPES.RESUME_POSITION);
    if (cachedPosition !== null) {
      console.log(`📦 使用全局缓存的断点续播位置: ${cachedPosition}秒`);
      return cachedPosition;
    }

    // 如果实例已经获取过，直接返回实例缓存的值
    if (this.resumePositionFetched) {
      console.log(`🔄 使用实例缓存的断点续播位置: ${this.resumePositionCache || 0}秒`);
      return this.resumePositionCache || 0;
    }

    try {
      console.log('🔍 从API获取断点续播位置...');
      const result = await StudyService.getLessonProgress(this.courseId, this.lessonId);

      if (result && result.code === 200 && result.data) {
        this.resumePositionCache = result.data.currentPosition || 0;
        this.resumePositionFetched = true;

        // 存储到全局缓存，短期缓存（2分钟）
        progressCache.set(
          this.courseId,
          this.lessonId,
          CACHE_TYPES.RESUME_POSITION,
          this.resumePositionCache,
          CACHE_EXPIRY.SHORT
        );

        console.log(`✅ 获取断点续播位置成功: ${this.resumePositionCache}秒`);
        return this.resumePositionCache;
      }
    } catch (error) {
      console.error('❌ 获取断点续播位置失败:', error);
    }

    // 获取失败时也标记为已获取，避免重复请求
    this.resumePositionFetched = true;
    this.resumePositionCache = 0;

    // 缓存失败结果，避免短期内重复请求
    progressCache.set(
      this.courseId,
      this.lessonId,
      CACHE_TYPES.RESUME_POSITION,
      0,
      CACHE_EXPIRY.SHORT
    );

    return 0;
  }

  /**
   * 手动触发进度上报
   */
  async forceReport(): Promise<LessonProgressResponse | null> {
    return await this.reportProgress(true);
  }

  /**
   * 更新配置
   */
  updateConfig(config: {
    reportInterval?: number;
    minWatchTime?: number;
    progressThreshold?: number;
  }): void {
    if (config.reportInterval) this.reportInterval = config.reportInterval;
    if (config.minWatchTime) this.minWatchTime = config.minWatchTime;
    if (config.progressThreshold) this.progressThreshold = config.progressThreshold;
    
    console.log('⚙️ 更新跟踪器配置:', config);
    
    // 重启定时器以应用新的间隔
    if (this.isTracking) {
      this.startReportTimer();
    }
  }

  /**
   * 销毁跟踪器
   */
  destroy(): void {
    this.stopTracking();
    console.log('🗑️ 销毁视频进度跟踪器');
  }
}
